var app = getApp();
module.exports = Behavior({
  data: {
    oneInd: 0,
    twoInd: 0,
    category: [],
    list: [],

    listHeight: [],
    twoHeight: [],
    getNextCateGood_Click: true,
    currentSection: null,
    touchStartY: 20,
    clickGoodNum: 0,
    prevScrollTop: 0,
    direction: "",
    timer: null,
    manyGood: [],
    Showspecs: false,
    moreCate: "",
    goodsCartsOld: "",
    childScroll: null,
    scrollTop: 0,
    stickyShow: false,
    cposHeight: 0,
    scrollAuto: false,
    refresherStatus: false,
    good_id: '',
  },
  methods: {
    async tapMore(e) {
      let {
        classid, item
      } = e.currentTarget.dataset;
      if (this.data.moreCate) {
        this.setData({
          moreCate: false,
          scrollAuto: true
        })
        return
      }
      let obj = {
        currentTarget: {
          dataset: {
            item: {
              id: classid
            }
          }
        }
      };
      await this.scrollToSection(obj);
      this.setData({
        moreCate: classid,
        scrollAuto: false
      })
    },
    binddragstart() {
      if (this.data.stickyShow) {
        this.setData({
          scrollAuto: true
        })
      } else {
        this.setData({
          scrollAuto: false
        })
      }
    },
    bindscrolltoupper() {
      let that = this;
      if (this.data.stickyShow) {
        this.setData({
          scrollAuto: false,
          refresherStatus: true
        })
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 100,
          success(res) {
            that.setData({
              refresherStatus: false,
              moreCate: ''
            })
          }
        })
      }else{
        wx.pageScrollTo({
          scrollTop:0,
          duration:100,
          success(res) {
            that.setData({
              refresherStatus: false,
              moreCate: ''
            })
          }
        })
      }
    },
    scrollChange(e) {
      let that = this;
      this.setData({
        stickyShow: e.detail.isFixed,
        scrollAuto: e.detail.isFixed
      })
      if (e.detail.isFixed) {
        let query = wx.createSelectorQuery();
        query.select('.pos').boundingClientRect();
        query.select('#head_top').boundingClientRect();
        query.select('.isTwoCateName').boundingClientRect();
        query.exec(function (res) {
          that.setData({
            cposHeight: res[0].height + res[1].height + (res[2].height / 2)
          })
        })
      }
    },
    getCateGood() {
      let urlStr = app.getNetAddresss(
        "plugin.chain-store.frontend.controller.index.category-goods"
      );
      app._getNetWork({
        url: urlStr,
        data: {
          category_id: this.data.category[this.data.oneInd].has_many_children[
            this.data.twoInd
          ].id,
          store_id: this.data.store_id,
          no_page: true,
        },
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            this.setData({
              ["category[" +
                this.data.oneInd +
                "].has_many_children[" +
                this.data.twoInd +
                "].good"
              ]: res.data.list,
            });
            this.observeSections();
            if (this.data.twoInd === 0) {
              this.setData({
                twoInd: this.data.category[0].has_many_children[0].id,
              });
            }
            if (this.data.oneInd === 0) {
              this.setData({
                oneInd: this.data.category[0].id
              })
            }
            console.log(this.data.oneInd, this.data.twoInd)
            this.get_Ind().then((res) => {
              let twoind = res.twoind;
              let oneind = res.oneind;
              if (
                twoind == 0 &&
                this.data.category[oneind].has_many_children.length > 1 &&
                this.data.category[oneind].has_many_children[twoind].good
                  .length < 10
              ) {
                let addNext = twoind + 1;
                let add =
                  this.data.category[oneind].has_many_children[addNext];
                this.getNextCateGood(add.id, addNext, oneind);
                return;
              }
            });
          }
        },
        fail: function (res) { },
      });
    },
    // async getNextCateGood(cateId, isTwoInd, isOneInd) {
    //   if (!this.data.getNextCateGood_Click) {
    //     return
    //   }
    //   this.data.getNextCateGood_Click = false;
    //   if (this.data.category[isOneInd].has_many_children[isTwoInd].good) {
    //     console.log('下一个子分类已经加载了商品')
    //     this.data.getNextCateGood_Click = true;
    //     return
    //   }
    //   this.getNextCateGood_Method(cateId, isTwoInd, isOneInd).then((res) => {
    //     this.data.getNextCateGood_Click = true;
    //     if (res.key == 'more') {
    //       // return this.getNextCateGood(add.id, addNext, res.isOneInd);
    //       console.log(res, '当前商品不够10个', this.data.category[res.isOneInd].has_many_children.length - 1, res.isTwoInd, res.isOneInd)
    //       if (this.data.category[res.isOneInd].has_many_children.length - 1 == res.isTwoInd) {
    //         console.log('当前商品不够10个，是最后一个二级了，切换一级分类')
    //         return this.getNextCateGood(this.data.category[res.isOneInd + 1].has_many_children[0].id, 0, res.isOneInd + 1);
    //       }
    //       return
    //     }
    //     if (res.isOneInd > 1) {
    //       console.log('then ===============1', res.isOneInd, this.data.category[res.isOneInd - 1].has_many_children[this.data.category[res.isOneInd].has_many_children.length - 1])
    //       let two = this.data.category[res.isOneInd].has_many_children.length - 1;
    //       if (this.data.category[res.isOneInd - 1].has_many_children[two]) {
    //         let addNext = res.isTwoInd + 1;
    //         let add = this.category[res.isOneInd].has_many_children[addNext];
    //         return this.getNextCateGood(add.id, addNext, res.isOneInd);
    //       }
    //     }
    //     if (this.data.category[res.isOneInd].has_many_children && this.data.category[res.isOneInd].has_many_children.length - 1 > res.isTwoInd) {
    //       console.log('then ===============2', this.data.category[res.isOneInd].has_many_children.length - 1 , res.isTwoInd)
    //       let addOneNext = res.isOneInd + 1;
    //       let addNext = 0;
    //       let add = this.data.category[addOneNext].has_many_children[addNext];
    //       return this.getNextCateGood(add.id, addNext, addOneNext);
    //     }
    //   }).then((res)=>{
    //     console.log(res,'================================================-----------------------------------')
    //   })
    // },
    /**
     * cateId { 需要加载商品的二级分类id }
     * isTwoInd { 所加载的二级索引 }
     * isOneInd { 所加载的一级索引 }
     */
    async getNextCateGood(cateId, isTwoInd, isOneInd, callback) {
      if (!this.data.getNextCateGood_Click) {
        return;
      }
      this.data.getNextCateGood_Click = false;
      let currentCategory = this.data.category[isOneInd].has_many_children[isTwoInd];
      if (currentCategory.good) {
        // console.log('下一个子分类已经加载了商品', currentCategory);
        if (callback) {
          this.setData({
            childScroll: callback,
          })
        }
        this.data.getNextCateGood_Click = true;
        return;
      }

      try {
        let res = await this.getNextCateGood_Method(cateId, isTwoInd, isOneInd);
        // console.log(callback)
        if (callback) {
          this.setData({
            childScroll: callback,
          })
        }
        this.data.getNextCateGood_Click = true;

        if (res.key === 'more') {
          if (this.data.category[isOneInd].has_many_children.length - 1 === isTwoInd) {
            // console.log('当前商品不够10个，是最后一个二级了，切换一级分类');
            await this.getNextCateGood(this.data.category[isOneInd + 1].has_many_children[0].id, 0, isOneInd + 1);
          }

          return;
        }

        if (isOneInd > 1 && this.data.category[isOneInd - 1].has_many_children[currentCategory.length - 1]) {
          // console.log('then ===============1', isOneInd, this.data.category[isOneInd - 1].has_many_children[currentCategory.length - 1]);
          let addNext = isTwoInd + 1;
          let add = this.category[isOneInd].has_many_children[addNext];
          await this.getNextCateGood(add.id, addNext, isOneInd);
        }

        if (currentCategory.length - 1 > isTwoInd) {
          // console.log('then ===============2', currentCategory.length - 1, isTwoInd);
          let addOneNext = isOneInd + 1;
          let addNext = 0;
          let add = this.data.category[addOneNext].has_many_children[addNext];
          await this.getNextCateGood(add.id, addNext, addOneNext);
        }
      } catch (error) {
        console.error(error);
      }
    },
    getNextCateGood_Method(cateId, isTwoInd, isOneInd) {
      return new Promise((resolve, reject) => {
        let urlStr = app.getNetAddresss(
          "plugin.chain-store.frontend.controller.index.category-goods"
        );
        app._getNetWork({
          url: urlStr,
          data: {
            category_id: cateId,
            store_id: this.data.store_id,
            no_page: true,
          },
          success: (resdata) => {
            this.data.getNextCateGood_Click = true;
            let res = resdata.data;
            if (res.result == 1) {
              this.setData({
                ["category[" +
                  isOneInd +
                  "].has_many_children[" +
                  isTwoInd +
                  "].good"
                ]: res.data.list,
              });
              console.log(res.data.list)
              if (res.data.list.length < 10) {
                resolve({
                  cateId,
                  isTwoInd,
                  isOneInd,
                  key: 'more'
                })
              } else {
                resolve({
                  cateId,
                  isTwoInd,
                  isOneInd
                })
              }
            }
          },
          fail: function (res) {
            this.data.getNextCateGood_Click = true;
          },
        });
      })
    },
    get_Ind() {
      return new Promise((resolve, reject) => {
        for (let i = 0; i < this.data.category.length; i++) {
          for (
            let k = 0; k < this.data.category[i].has_many_children.length; k++
          ) {
            if (
              this.data.twoInd == this.data.category[i].has_many_children[k].id
            ) {
              let json = {
                oneind: i,
                twoind: k,
              };
              this.setData({
                oneInd: this.data.category[i].id
              })
              resolve(json);
            }
          }
        }
      });
    },
    async scrollToSection(e) {
      console.log(this.data.stickyShow)
      await this.autoSticky()
      let {
        item
      } = e.currentTarget.dataset;

      let ind = await this.getOneType(item.id);
      let oneind = ind;
      let twoind = 0;
      let callback = `sid${item.id}`;
      this.getNextCateGood(this.data.category[oneind].has_many_children[twoind].id, twoind, oneind, callback).then(() => {
        setTimeout(() => {
          this.setData({
            oneInd: this.data.category[ind].id
          })
        }, 100);
      });
    },
    yz_goodsPopupClose() {
      this.setData({
        good_id: '',
        scrollAuto: false
      })
      this.updateCart();
    },
    tapGood(e) {
      let id = e.currentTarget.dataset.good.id;
      this.setData({
        good_id: id,
        scrollAuto: true
      })
    },
    async scrollToTwoCate(e) {
      await this.autoSticky()
      if (this.data.moreCate) {
        this.setData({
          moreCate: false,
          scrollAuto: true
        })
      }
      let that = this;
      let {
        twoitem,
        indx,
        indexone
      } = e.currentTarget.dataset;

      let oneind = indexone;
      let twoind = indx;

      await that.getNextCateGood(that.data.category[oneind].has_many_children[twoind].id, twoind, oneind)
      let query = wx.createSelectorQuery();
      query.select(`#sid${twoitem}`).boundingClientRect();
      query.select('.scroll_view').fields({
        dataset: true,
        size: true,
        scrollOffset: true,
        properties: ['scrollX', 'scrollY'],
        computedStyle: ['margin', 'backgroundColor'],
        context: true,
      })
      query.select('.isTwoCateName').boundingClientRect();
      query.select('.pos').boundingClientRect();
      query.exec(function (rect) {
        console.log(rect[0].top + rect[1].scrollTop - (rect[2].height + rect[3].height))
        if (rect[0].top != 0) {
          that.setData({
            scrollTop: rect[0].top + rect[1].scrollTop - (rect[2].height + rect[3].height + 30)
          })
          setTimeout(() => {
            that.setData({
              oneInd: that.data.category[indexone].id
            })
          }, 100);
        }
      })
    },
    autoSticky() {
      let that = this;
      return new Promise((resolve, reject) => {
        if (!this.data.stickyShow) {
          let query = wx.createSelectorQuery();
          query.select('.goodBox').boundingClientRect();
          query.exec(function (res) {
            wx.pageScrollTo({
              scrollTop: res[0].top + that.data.statusBarHeight,
              success() {
                resolve()
              }
            })
          })
        } else {
          resolve()
        }
      })

    },
    getOneType(id) {
      let arr = this.data.category;
      return new Promise((resolve, reject) => {
        for (let i = 0; i < arr.length; i++) {
          // console.log(arr[i])
          if (arr[i].id == id) {
            resolve(i)
          }
        }
      })
    },
    observeSections() {
      // let firstId = this.data.category[0].has_many_children[0].id;
      this.data.observer = wx.createIntersectionObserver(this, {
        observeAll: true,
        thresholds: [0, 1],
      });
      this.data.observer.relativeTo(".cpos").observe(".cateGood", (res) => {
        if (res.intersectionRatio == 0) return;
        this.setData({
          currentSection: res.dataset.id,
          twoInd: res.dataset.id,
        });
      });
    },
    onIntersection(e) {
      console.log(e);
    },
    bindscroll(e) {
      // console.log(e);
      this.get_Ind().then((res) => {
        let twoind = res.twoind;
        let oneind = res.oneind;
        // console.log(this.data.category[oneind].has_many_children, twoind, oneind, 'bindscroll')
        if (this.data.category[oneind].has_many_children.length - 1 == twoind) {
          // console.log(this.data.category, oneind, 'asssssssssssssssssssssssssssssssssss')
          if (this.data.category.length - 1 == oneind) {
            let addOneNext = oneind;
            let addNext = 0;
            let add = this.data.category[addOneNext].has_many_children[addNext];
            console.log("当前是最后一个一级了", this.data.category[addOneNext].has_many_children[addNext]);
            this.getNextCateGood(add.id, addNext, addOneNext);
            return
          } else {
            let addOneNext = oneind + 1;
            let addNext = 0;
            let add = this.data.category[addOneNext].has_many_children[addNext];
            console.log("还有下一个一级", this.data.category[addOneNext].has_many_children[addNext]);
            this.getNextCateGood(add.id, addNext, addOneNext);
            return
          }
        }
        this.getNextCateGood(this.data.category[oneind].has_many_children[twoind + 1].id, twoind + 1, oneind);
      });
    },
  },
});